package com.gylang.commons.util;

import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * 处理返回博客连接url
 *
 * @author gylang,
 * date 2020/4/23,
 * @version 1.0
 */
public class UrlUtils {

    /**
     * 添加请求参数
     *
     * @param domain url基址
     * @param params RequestParam 参数
     * @return url
     */
    public static String toUrl(String domain, Map<String, String> params) {

        return addParams(domain, params);
    }

    public static String toUrl(String domain, String pathVariable, Map<String, String> params) {

        if (StringUtils.isNotBlank(pathVariable)) {
            return addParams(domain + pathVariable, params);
        } else {
            return addParams(domain, params);
        }
    }

    private static String addParams(String domain, Map<String, String> params) {

        StringBuilder url = new StringBuilder(domain);
        //不需要设置参数
        if (CollectionUtils.isEmpty(params)) {
            return domain;
        } else {
            //url 参数前缀
            url.append('?');
            for (Map.Entry<String, String> param : params.entrySet()) {
                url.append(param.getKey())
                        .append('=')
                        .append(param.getValue())
                        .append('&');
            }
            //去除尾部 ‘&’
            url.deleteCharAt(url.length() - 1);
            return url.toString();
        }
    }
}

